package com.littlecar.security.controller;

import com.littlecar.security.entity.User;
import com.littlecar.security.utils.JwtUtil;
import com.littlecar.security.utils.RedisUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 描述：
 *
 * @author littlecar
 * @date 2020/2/29 10:52
 */
@Controller
public class LoginController {

    @Autowired
    private RedisUtil redisUtil;

    @RequestMapping("/login")
    public String login() {
        return "login";
    }

    @RequestMapping("/loginSuccess")
    public String loginSuccess(HttpServletRequest request, HttpServletResponse response) {
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String token = JwtUtil.createToken(user);
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            if (StringUtils.equals(cookie.getName(), "UserToken")) {
                redisUtil.set(cookie.getValue(), token, JwtUtil.EXPIRE);
            }
        }
        return "success";
    }
}
